package com.shaozi.nc.data.mongodao;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.shaozi.data.cache.pojo.CommonQueuePojo;
import com.shaozi.data.cache.redis.CommonQueueRDao;
import com.shaozi.data.mongo.dao.SZMongoBaseDao;
import com.shaozi.lib.logger.DBLogger;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.model.LogModel;
import com.shaozi.utils.common.JsonUtil;

/**
 * 通用日志
 * 
 * @author xueshuwu
 * 
 */
@Repository("logMDao")
public class LogMDao extends SZMongoBaseDao<LogModel> implements DBLogger {

	private Logger logger = Logger.getLogger(LogMDao.class);
	@Autowired
	private CommonQueueRDao commonQueueRDao;

	@Autowired
	public LogMDao(MongoTemplate shaoziTemplate) {
		super(shaoziTemplate);
	}

	@Override
	public void save(String sharding, String logType, String logText, String extraId, Integer level, String uuid) {
		LogModel log = new LogModel();
		log.setLevel(level);
		log.setLogType(logType);
		log.setLogText(logText);
		log.setExtraId(extraId);
		log.setUuid(uuid);
		save(sharding, log);
	}

	@Override
	public void save(String sharding, String logType, String logText, String extraId, Integer level) {
		this.save(sharding, logType, logText, extraId, level, null);
	}

	public void save(String compId, LogModel model) {
		model.setCreateTime(System.currentTimeMillis());
		StringBuffer shardingId = new StringBuffer();
		if (!StringUtils.isEmpty(compId)) {
			model.setCompanyId(compId);
			// shardingId.append(compId).append("_");
		}
		DateFormat df = new SimpleDateFormat("yyyyMM");
		shardingId.append(df.format(new Date(model.getCreateTime())));
		try {
			CommonQueuePojo pojo = new CommonQueuePojo(getCollectionName(shardingId.toString()),
					JsonUtil.toJsonString(model));
			commonQueueRDao.pushValue(null, pojo);
		} catch (SzException e) {
			logger.warn(SzException.getStackMessage(e));
		}
	}

}
